// 后台服务 worker - 核心消息检查逻辑
class MessageNotifier {
  constructor() {
    this.lastMessageId = null;
    this.isRunning = false;
    this.init();
  }

  async init() {
    // 加载保存的设置
    const result = await chrome.storage.sync.get([
      'apiUrl',
      'pollInterval',
      'lastMessageId',
      'isRunning'
    ]);
    
    this.lastMessageId = result.lastMessageId || null;
    this.isRunning = result.isRunning || false;
    
    if (result.apiUrl && this.isRunning) {
      this.startPolling(result.pollInterval || 30);
    }
    
    console.log('消息通知器已初始化', {
      isRunning: this.isRunning,
      lastMessageId: this.lastMessageId
    });
  }

  // 模拟API调用 - 在实际使用中替换为真实的API端点
//   async fetchMessages(apiUrl) {
//     try {
//       // 这里模拟API响应
//       // 实际使用时替换为: const response = await fetch(apiUrl);
//       await new Promise(resolve => setTimeout(resolve, 1000));
      
//       // 模拟数据 - 50%概率返回新消息
//       if (Math.random() > 0.5) {
//         const newMessage = {
//           id: Date.now(),
//           content: `新消息到达！时间: ${new Date().toLocaleTimeString()}`,
//           timestamp: new Date().toISOString(),
//           type: 'info'
//         };
//         return [newMessage];
//       }
//       return [];
//     } catch (error) {
//       console.error('获取消息失败:', error);
//       throw error;
//     }
//   }

async fetchMessages(apiUrl) {
  try {
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP错误! 状态码: ${response.status}`);
    }
    
    const resultData = await response.json();
    
    // 检查响应码
    if (resultData.code !== 200) {
      throw new Error(`API返回错误: ${resultData.msg || '未知错误'}`);
    }
    
    // 直接处理单条消息
    if (resultData.data) {
      const newMessage = {
        id: Date.now(),
        content: resultData.data, // "测试消息"
        timestamp: new Date().toISOString(),
        type: 'info'
      };
      return [newMessage];
    }
    
    return [];
    
  } catch (error) {
    console.error('获取消息失败:', error);
    this.showErrorNotification(`获取消息失败: ${error.message}`);
    throw error;
  }
}

  // 检查新消息
  async checkForNewMessages() {
    if (!this.isRunning) return;

    debugger
    const result = await chrome.storage.sync.get(['apiUrl']);
    const { apiUrl } = result;

    if (!apiUrl) {
      console.log('未设置API URL');
      return;
    }

    try {
      const messages = await this.fetchMessages(apiUrl);
      
      if (messages.length > 0) {
        const latestMessage = messages[0];
        
        // 如果是第一条消息或新消息
        if (!this.lastMessageId || latestMessage.id > this.lastMessageId) {
          this.lastMessageId = latestMessage.id;
          
          // 保存最新消息ID
          await chrome.storage.sync.set({ lastMessageId: this.lastMessageId });
          
          // 显示通知
          this.showNotification(latestMessage);
          
          // 发送消息到popup（如果打开的话）
          this.sendMessageToPopup('NEW_MESSAGE', latestMessage);
        }
      }
    } catch (error) {
      console.error('检查消息时出错:', error);
      this.showErrorNotification('获取消息失败: ' + error.message);
    }
  }

  // 显示浏览器通知
  showNotification(message) {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: '新消息通知',
      message: message.content,
      contextMessage: '消息通知器',
      priority: 2,
      eventTime: Date.now() + 5000
    });
  }

  // 显示错误通知
  showErrorNotification(errorMessage) {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: '消息检查错误',
      message: errorMessage,
      contextMessage: '消息通知器',
      priority: 2
    });
  }

  // 发送消息到popup
  sendMessageToPopup(type, data) {
    chrome.runtime.sendMessage({
      type: type,
      data: data
    }).catch(() => {
      // Popup未打开时会有错误，可以忽略
    });
  }

  // 开始轮询
  async startPolling(intervalInSeconds = null) {
  // 如果没有传入间隔，从存储中读取
  if (intervalInSeconds === null) {
    const result = await chrome.storage.sync.get(['pollInterval']);
    intervalInSeconds = result.pollInterval || 30;
  }
  
  // 先停止现有的轮询
  if (this.isRunning) {
    await chrome.alarms.clear('messagePoll');
  }
  
  this.isRunning = true;
  
  // 创建新警报
  chrome.alarms.create('messagePoll', {
    periodInMinutes: intervalInSeconds / 60
  });
  
  // 立即检查一次
  this.checkForNewMessages();
  
  // 保存状态
  await chrome.storage.sync.set({ 
    isRunning: true,
    pollInterval: intervalInSeconds
  });
  
  console.log(`开始轮询，间隔: ${intervalInSeconds}秒`);
}
  // 停止轮询
  async stopPolling() {
    this.isRunning = false;
    await chrome.alarms.clear('messagePoll');
    await chrome.storage.sync.set({ isRunning: false });
    console.log('停止轮询');
  }
}

// 初始化通知器
const notifier = new MessageNotifier();

// 监听警报 - 定时检查消息
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'messagePoll') {
    notifier.checkForNewMessages();
  }
});

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.type) {
    case 'START_POLLING':
      notifier.startPolling(request.interval);
      sendResponse({ success: true });
      break;
      
    case 'STOP_POLLING':
      notifier.stopPolling();
      sendResponse({ success: true });
      break;
      
    case 'TEST_NOTIFICATION':
      notifier.showNotification({
        content: '这是一条测试消息',
        timestamp: new Date().toISOString()
      });
      sendResponse({ success: true });
      break;
      
    case 'GET_STATUS':
      sendResponse({
        isRunning: notifier.isRunning,
        lastMessageId: notifier.lastMessageId
      });
      break;
  }
});

// 安装时的初始化
chrome.runtime.onInstalled.addListener(() => {
  console.log('消息通知器插件已安装');
  
  // 设置默认配置
  chrome.storage.sync.set({
    pollInterval: 30,
    apiUrl: 'https://api.example.com/messages',
    isRunning: false
  });
});